package com.hd123.rumba.qt.def;

import java.util.ArrayList;
import java.util.List;

import com.hd123.rumba.exception.BusinessException;

public class SQLCriteriaList extends ArrayList<SQLCriteria> implements List<SQLCriteria> {
    private QueryDefinition query=null;
    
	public QueryDefinition getQuery() {
      return query;
    }

    public void setQuery(QueryDefinition query) {
      this.query = query;
    }

  /**
	 * @param clauseType 取值WHERECLAUSE, HAVINGCLAUSE
	 * @return
	 * @throws BusinessException
	 */
	public String getSQLClause(int clauseType) throws BusinessException {
		StringBuffer sb = new StringBuffer();
		int m = 0;
		for (int j = 0; j < size(); ++j) {
			SQLCriteria item = (SQLCriteria) get(j);
            // 要-1: 最后一行是checkbox的值. 07-01-19
			if (m < item.getRights().size() - 1) 
				m = item.getRights().size() - 1;
			if (item.isRequired() && (item.getRights().get(0) == null
					|| ((String) item.getRights().get(0)).trim().equals("")))
				throw new BusinessException("必须输入条件" + query.getTitleByColumn(item.getLeft())
						+ query.getOperatorName(item.getOperator()));
		}

		boolean first = true;

		for (int j = 0; j < m; ++j) {
			boolean first2 = true;
			StringBuffer sb2 = new StringBuffer();
			for (int i = 0; i < size(); ++i) {
				SQLCriteria item = (SQLCriteria) get(i);
				String t = item.getSQLExpression(clauseType, j);
				// if (!item.isHaving() && t != null) {
                if (t != null) {
					if (first2) {
						sb2.append("(");
						first2 = false;
					} else
						sb2.append(" and ");
					sb2.append("(");
					sb2.append(t);
					sb2.append(")");
				}
			}
			if (sb2.length() > 0)
				sb2.append(")");
			if (first && sb2.length() > 0) {
				sb.append(sb2);
				first = false;
			} else if (sb2.length() > 0) {
				sb.append("\n or ");
				sb.append(sb2);
			}
		}
		return sb.length() == 0 ? null : sb.toString();
	}

	public String debugInfo() {
		StringBuffer sb = new StringBuffer();
		sb.append(getClass().getName() + "\n");
		for (int i = 0; i < size(); ++i) {
			SQLCriteria item = (SQLCriteria) get(i);
			sb.append(i + ": " + item.debugInfo() + "\n");
		}
		return sb.toString();
	}
}
